package com.ccsc.auth.controller;

import com.ccsc.auth.global.Constants;
import com.ccsc.auth.service.UserService;
import com.ccsc.auth.utils.BaseResponse;
import com.ccsc.auth.utils.DataMap;
import com.ccsc.auth.utils.DateUtil;
import com.ccsc.auth.utils.MD5;
import com.google.common.base.Strings;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.WebRequest;

/**
 * Created by XingWen on 2016/3/29.
 */

@RestController
@RequestMapping("/authVerify")
public class AuthVerifyController extends BaseController {
    @Autowired
    private UserService userService;

    //登录认证
    @RequestMapping(value = "/login", method = RequestMethod.GET, produces = {"application/json", "application/xml"})
    public BaseResponse sysLogin(WebRequest request) throws Exception {
        Session session = getSession();
        DataMap params = getParam(request);
        String account = params.getString("username");
        String pwd = params.getString("password");
        String verifyCode = params.getString("verify");
        String sessionCode = (String) session.getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);

        if (Strings.isNullOrEmpty(verifyCode) || Strings.isNullOrEmpty(sessionCode) || !verifyCode.equalsIgnoreCase(sessionCode)) {
            return this.ok(0);
        }

        Subject currentUser = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(account, MD5.MD5Encode(pwd));

        try {
            currentUser.login(token);
            return this.ok(MD5.MD5Encode(Constants.SSO_SECRET_KEY + token.getUsername() + DateUtil.getDate()));
        } catch (AuthenticationException e) {
            token.clear();
            return this.error(101, getMessageSource("101"));
        }
    }

    //注销
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public BaseResponse sysLogout(WebRequest request) throws Exception {
        try {
            Subject currentUser = SecurityUtils.getSubject();
            currentUser.logout();
            return this.ok(1);
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
            return this.error(500);
        }
    }
}
